<script lang="ts" setup>
import { QForm, type FormItemRows } from '@meetjs/element-plus-kit'
import { type FormRules } from 'element-plus'
import type { IGetGenTableRes } from '@/api/code/gen/type'

const props = defineProps<{
	info: IGetGenTableRes['data']['info']
}>()

const formRef = ref()
const formData = ref<any>({
	tableName: '',
	tableComment: '',
	className: '',
	functionAuthor: '',
	remark: ''
})

watch(
	() => props.info,
	value => {
		Object.keys(formData.value).forEach(key => {
			if (Object.prototype.hasOwnProperty.call(value, key)) {
				formData.value[key] = (value as any)[key]
			}
		})
	},
	{ immediate: true }
)

const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '表名称',
		prop: 'tableName'
	},
	{
		type: 'input',
		label: '表描述',
		prop: 'tableComment'
	},
	{
		type: 'input',
		label: '实体类名称',
		prop: 'className'
	},
	{
		type: 'input',
		label: '作者',
		prop: 'functionAuthor'
	},
	{
		type: 'textarea',
		label: '备注',
		prop: 'remark',
		attrs: {
			rows: 4
		}
	}
])

const rules = reactive<FormRules<{ [k: string]: any }>>({
	tableName: [
		{
			required: true,
			message: '请输入表名称',
			trigger: 'blur'
		}
	],
	tableComment: [
		{
			required: true,
			message: '请输入实体类名称',
			trigger: 'blur'
		}
	],
	className: [
		{
			required: true,
			message: '请输入表描述',
			trigger: 'blur'
		}
	],
	functionAuthor: [
		{
			required: true,
			message: '请输入作者',
			trigger: 'blur'
		}
	]
})

function validate() {
	return new Promise((resolve, reject) => {
		formRef.value?.validate((valid: boolean) => {
			if (valid) {
				resolve(true)
			} else {
				reject(new Error('表单验证失败'))
			}
		})
	})
}

function getData() {
	return formData.value
}

defineExpose({
	validate,
	getData
})
</script>

<template>
	<QForm
		ref="formRef"
		label-width="150px"
		:model="formData"
		:form-options="formOptions"
		:rules="rules"
	/>
</template>

<style scoped lang="scss"></style>
